package com.baitiaojun.common.manager;

import com.baitiaojun.common.utils.thread.ThreadsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.TimerTask;
import java.util.concurrent.*;

@Slf4j
@Component
public class AsyncManager {

    @Autowired
    private ScheduledExecutorService scheduledExecutorService;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    private static final int DELAY_TIME = 10;

    private AsyncManager() {}

    public Future<?> execute(Callable<?> callable) {
        log.warn("异步线程池开始执行任务");
        if (threadPoolTaskExecutor != null) {
            return threadPoolTaskExecutor.submit(callable);
        }
        return new FutureTask<>(callable);
    }

    public void execute(Runnable runnable) {
        log.warn("异步线程池开始执行任务");
        if (threadPoolTaskExecutor != null) {
            threadPoolTaskExecutor.execute(runnable);
        }
    }

    public void execute(TimerTask timerTask) {
        log.warn("定时异步线程池开始执行任务");
        if (scheduledExecutorService != null) {
            scheduledExecutorService.schedule(timerTask, DELAY_TIME, TimeUnit.MILLISECONDS);
        }
    }

    /**
     * 手动关闭线程池
     */
    public void shutdown() {
        log.warn("执行异步线程池关闭");
        ThreadsUtils.shutdown(scheduledExecutorService);
    }

    /**
     * 应用程序关闭前自动执行此方法确保能关闭后台任务的线程池
     */
    @PreDestroy
    public void autoShutdown() {
        log.warn("执行自动异步线程池关闭");
        ThreadsUtils.shutdown(scheduledExecutorService);
    }
}
